/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.wikimark.http;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;

/**
 * The abstract HTTP POST request formatter 
 * @author Sergey I. Salishev
 */
public abstract class AbstractPostRequest {
	/**
	 * the buffer for accumulating formatted request
	 */
	protected final StringBuilder request = new StringBuilder();
	
	private final String pathInfo;
			
	/**
	 * @param pathInfo the info encoded in url path suffix
	 */
	public AbstractPostRequest(String pathInfo) {
		this.pathInfo = pathInfo;		
	}
	
	void post(HttpURLConnection connection) throws IOException {
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", getContentType());
		connection.setDoOutput(true);
		Writer w = new OutputStreamWriter(connection.getOutputStream(), "utf-8");		
		w.write(getContentString());
		w.flush();
	}
	
	/**
	 * @return the PATH_INFO part of the url
	 */
	public String getPathInfo() {
		return pathInfo;
	}
		
	/**
	 * @return content-type header value
	 */
	public abstract String getContentType();
	
	/**
	 * Finalizes the request and returns content. After the call no other 
	 * {@link #addParameter(String, String)} is allowed.
	 * @return the HTTP request content
	 */
	public abstract String getContentString();
	
	/**
	 * Adds parameter to the request. Parameters can be added befor fist 
	 * {@link #getContentString()} request.
	 * @param name parameter name
	 * @param value parameter value
	 */
	public abstract void addParameter(String name, String value);
	
}
